// components/detail-header/index.js
import {
  modelApi
} from "../../api/index.js"
const app = getApp();
Component({
  properties: {
    headData: {
      type: Object,
      value: {}
    },
  },
  lifetimes: {
    attached() {
      let _this = this
      wx.getSystemInfo({
        success: (res) => {
          let systemInfo = wx.getSystemInfoSync();
          let info = wx.getMenuButtonBoundingClientRect();
          _this.setData({
            navTop: res.statusBarHeight,
            navHeight: (info.top - systemInfo.statusBarHeight) * 2 + info.height,
          });
        }
      });
      setTimeout(() => {
        this.isSelf(this.properties.headData)
        this.checkFollow(this.properties.headData)
      }, 300)
    },
  },


  /**
   * 组件的初始数据
   */
  data: {
    navObjWid: app.globalData.navObjWid,
    isSelf: false, //是否是作者
    isFollow: false, //是否已关注
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 返回
    goBack() {
      // console.log('返回');
      wx.navigateBack({
        success(){
          console.log('返回成功');
        },
        fail(){
          console.log('返回失败');
          wx.switchTab({
            url: '/pages/ai/index',
          })
        }
      })
    },
    // 关注作者
    async Ifollow(e) {
      const _this = this;
      modelApi[this.data.isFollow ? "removefollow" : "addfollow"]({
          ID: this.properties.headData.userId,
        })
        .then((res) => {
          if (res.StatusCode === 200) {
            this.setData({
              isFollow: !_this.data.isFollow,
            });
            wx.showToast({
              title: _this.data.isFollow ? "关注成功" : "取关成功",
              mask: "true",
            });
          }
        })
        .catch((err) => {
          if (err.statusCode === 401) {
            // _this.shudLogin(true);
            console.log('调用父组件方法去登录');
            _this.triggerEvent('login')
          }
        });
    },
    //判断是否关注
    async checkFollow(v) {
      // 登录了才调用
      let token = wx.getStorageSync("token");
      if (token) {
        let res = await modelApi.isfollowtouser({
          ID: v.userId,
        });
        this.setData({
          isFollow: res.Result,
        });
      }
    },
    // 是否是作者
    isSelf(v) {
      // console.log('user', wx.getStorageSync('userInfo'));
      // console.log('作者', v);
      if (v.userId === wx.getStorageSync('userInfo')?.userId) {
        this.setData({
          isSelf: true
        })
      }else{
        this.setData({
          isSelf: false
        })
      }
    },
    
  }
})